/**
 ***********************************************************************
 * Program name: EmailSender.java<br>
 * Program description: TODO<br>
 * Author: sugen<br>
 * Revision history:1.0<br>
 * <br>
 * Description of Change	Programmer		Date<br>
 * ---------------------    ----------      ----<br>
 * Initial creation			Su Gen		   2011-3-9 <br>
 * <br>
 * Copyright (c) 2011 by SUGEN ALL RIGHTS RESERVED<br>
 ************************************************************************
 */
package com.mail;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.log4j.Logger;
import com.mail.EmailSenderAuthenticator;
import com.common.StringUtil;

public class EmailSender {
	
	private String smtpServer = "smtp.qq.com" ;
	private String smtpUser = "alertmail";
	private String smtpPassword = "washington314";
	private String emailEncoding = "utf-8";
	private String emailFrom = "alertmail@qq.com";
	private String emailFromName = "Alert Messager";
	private Logger log=Logger.getLogger(EmailSender.class);
	
	public String getEmailFrom() {
		return emailFrom;
	}
	public void setEmailFrom(String emailFrom) {
		this.emailFrom = emailFrom;
	}
	
	public String getEmailEncoding() {
		return emailEncoding;
	}
	public void setSmtpServer(String smtpServer) {
		this.smtpServer = smtpServer;
	}
	public void setEmailEncoding(String emailEncoding) {
		this.emailEncoding = emailEncoding;
	}
	public void setSmtpUser(String smtpUser) {
		this.smtpUser = smtpUser;
	}
	public void setSmtpPassword(String smtpPassword) {
		this.smtpPassword = smtpPassword;
	}
	
	public  boolean send(String to, String subject, String text, String attachment)
	{
		return send(to,this.emailFrom,this.emailFromName,subject,text,attachment);
	}	
	
	public  boolean send(String to, String from, String fromName, String subject, String text, String attachment) {
		if (to == null || to.trim().equals("")||text.equals("")) return false;
		
		try {
			Properties props = System.getProperties();
					
			Authenticator authenticator = null;
			if (smtpServer != null) props.put("mail.smtp.host", smtpServer);
			props.put("mail.transport.protocol", "smpt");
			props.put("mail.smtp.auth", "true");
			authenticator = new EmailSenderAuthenticator(smtpUser,smtpPassword);
			Session session = Session.getInstance(props, authenticator);
			session.setDebug(true);
			Message msg = new MimeMessage(session);

			if (from != null) msg.setFrom(new InternetAddress(from, fromName, emailEncoding));
			else msg.setFrom();
			log.debug("email title is " + subject);
			log.debug("email from address  is " + from);
			
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
			sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
			if(subject == null){
				subject = "";
			}
			//mail为乱码,先注释掉该行代码--wenkai
			//subject = "=?" + emailEncoding + "?B?" + enc.encode(subject.getBytes(emailEncoding)) + "?=";// add by wang.hui
			msg.setSubject(subject);

			MimeMultipart mp = new MimeMultipart();

			mp.setSubType("alternative");
			if (text != null) {
				//添加纯文本部分内容
				MimeBodyPart mbp1 = new MimeBodyPart();
				mbp1.setContent(text, "text/html");
				//mail为乱码,先注释掉该行代码--wenkai
				//mbp1.setContent(text, "text/html;charset=" + emailEncoding);
				mbp1.setHeader("Content-Transfer-Encoding", "base64");
				mp.addBodyPart(mbp1);
				
				
			}
			log.debug("email content  is " + text);
			//attachment
			if(null != attachment && !"".equals(attachment)){
				BodyPart mbp3 = new MimeBodyPart();
				FileDataSource fds = new FileDataSource(attachment);
				DataHandler dh = new DataHandler(fds);
				mbp3.setDataHandler(dh);
				mbp3.setHeader("Content-Transfer-Encoding", "base64");
				mbp3.setFileName(fds.getName());
				mp.addBodyPart(mbp3);
			}else{
				mp.setSubType("alternative");
			}
			log.debug("attachment name is " + attachment);
			msg.setContent(mp);
			msg.setSentDate(new Date());
			Transport.send(msg);
			System.out.println(" Send OK ");
			return true;
		} catch (Exception e) {
			log.error(e);
			return false;
		}
	}
		
	public String getEmailFromName() {
		return emailFromName;
	}
	public void setEmailFromName(String emailFromName) {
		this.emailFromName = emailFromName;
	}
	
	public boolean send(String fromName, String from, List<String> toArray, List<String> ccArray, 
			String subject, List<String> attachArray, String text) {
		if ((toArray == null || toArray.size() == 0) 
				&& (ccArray == null || ccArray.size() == 0)){
			return false;
		}
		
		try {
			Properties props = System.getProperties();
			
			if (smtpServer != null) {
				props.put("mail.smtp.host", smtpServer);
			}
			
			Authenticator auth = new EmailSenderAuthenticator(smtpUser, smtpPassword);
			
			Session session = Session.getInstance(props, auth);
			session.setDebug(true);
			
			Message msg = new MimeMessage(session);
			
			//Set mail from
			if (StringUtil.checkIsNull(from)) {
				from = getEmailFrom();
				fromName = getEmailFromName();
			}
			
			msg.setFrom(new InternetAddress(from, fromName, emailEncoding));
			log.debug("Mail from address  is " + from);
			
			//Set mail to
			if (toArray != null && toArray.size() > 0) {
				log.debug("The to is:" + "\n\r");
				InternetAddress[] toAddress = new InternetAddress[toArray.size()];
				
				for (int i = 0; i < toArray.size(); i++) {
					toAddress[i] = new InternetAddress(toArray.get(i));
					
					log.debug(toAddress[i] + "\n\r");
				}

				msg.setRecipients(Message.RecipientType.TO, toAddress);
			}
			
			//Set mail cc
			if (ccArray != null && ccArray.size() > 0) {
				log.debug("The cc is:" + "\n\r");
				InternetAddress[] ccAddress = new InternetAddress[ccArray.size()];
				for (int i = 0; i < ccArray.size(); i++) {
					ccAddress[i] = new InternetAddress(ccArray.get(i));
					
					log.debug(ccAddress[i] + "\n\r");
				}

				msg.setRecipients(Message.RecipientType.CC, ccAddress);
			}
			
			//Set mail subject			
			sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
			
			if (subject == null) {
				subject = "";
			}
			
			subject = "=?" + emailEncoding + "?B?" + enc.encode(subject.getBytes(emailEncoding)) + "?=";
			
			msg.setSubject(subject);
			
			log.debug("Mail subject is " + subject);
			
			MimeMultipart mp = new MimeMultipart();
			
			//Set mail attachment
			if (attachArray != null && attachArray.size() > 0) {
				log.debug("The attachment is:" + "\n\r");

				for (int i = 0; i < attachArray.size(); i++) {
					BodyPart tmBodyPart = new MimeBodyPart();
					File file = new File(attachArray.get(i));
					FileDataSource fds = new FileDataSource(file);
					DataHandler dh = new DataHandler(fds);
					tmBodyPart.setDataHandler(dh);
					tmBodyPart.setHeader("Content-Transfer-Encoding", "base64");
					tmBodyPart.setFileName(fds.getName());
					mp.addBodyPart(tmBodyPart);

					log.debug(attachArray.get(i) + "\n\r");
				}
			}
			
			//Set mail body
			if (text != null) {
				MimeBodyPart bodyPart = new MimeBodyPart();
				bodyPart.setContent(text, "text/html;charset=" + emailEncoding);
				bodyPart.setHeader("Content-Transfer-Encoding", "base64");
				mp.addBodyPart(bodyPart);

				log.debug("Mail content is " + text);
			}
			
			msg.setContent(mp);
			msg.setSentDate(new Date());
			Transport.send(msg);
			
			return true;
		} catch (Exception e) {
			log.error(e);
			
			return false;
		}
	}
}

